#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'YC'

import os
import platform
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator, FormatStrFormatter  


def statisticSingle(retfilename):
    lamda = 0.8

    if os.path.isfile(retfilename):
        lineindex = 0
        cariancesum = 0
        timeusedsum = 0
        carianceresult = list()
        timeusedresult = list()
        for line in open(retfilename):
            if 0 < lineindex and 10 >= lineindex:
                line = line.strip("\n")
                data = line.split("\t")
                cariancesum += float(data[0])
                timeusedsum += int(data[1])
                #print("%f" % float(data[0]))
                if lineindex == 10:
                    carianceresult.append(cariancesum/lineindex)
                    timeusedresult.append(timeusedsum/lineindex)
                    cariancesum = 0
                    timeusedsum = 0
                    lineindex = 1
                else:
                    lineindex += 1
            else:
                lineindex = 1
        new_carianceresult = [int(float("%.7f" % float(i))*1e07) for i in carianceresult]
        #print(new_result)
        #print(result)
        reretFile = open("re_"+retfilename,"w")
        reretFile.write("cariance+timeused (expectation)\n")
        cariance_timeused_result = [lamda*x+(1-lamda)*y for x,y in zip(new_carianceresult,timeusedresult)]
        for cariance_timeused in cariance_timeused_result:
            reretFile.write("%d\n" % cariance_timeused)
        reretFile.close()
        return cariance_timeused_result
        
    else:
        print("File name "+retfilename+" error !")
        return
    
def computeExpectation(data):
    return sum(data)/len(data)

def autolabel(rects,ax):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x()+rect.get_width(), 1.*height, '%d'%int(height),
                ha='center', va='bottom')

def createAverage(datamaplist):
    yminorLocator   = MultipleLocator(100) #将此y轴次刻度标签设置为0.1的倍数
    RNGs=list()
    data_list=list()
    for element in datamaplist:
        for RNG in element:
            RNGs.append(RNG)
            print(RNG)
            data_list.append(sum(element[RNG])/len(element[RNG]))
    x = np.arange(1,len(RNGs)+1)
    fig, ax = plt.subplots()
    #print("namelen: %d ",len(x),",datalistlen:",len(data_list))
    
    width=0.5 #the width of bars
    
    rect1 = plt.bar(x, data_list,width,color="orange",linewidth=0,xerr=(0.1,0.1,0.1,0.1),yerr=(200,200,200,200))
    ax.set_ylim(4000,9000)
    ax.set_xlim(0.5, len(RNGs)+1)
    ax.yaxis.set_minor_locator(yminorLocator)
    ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度
    autolabel(rect1,ax)
    plt.xticks(x+width/2,RNGs)
    plt.ylabel('Expectation(V_RNG)')
    plt.savefig(os.getcwd()+"/AverageRet.png")
    

if __name__ == "__main__":
    xmajorLocator   = MultipleLocator(1) #将x主刻度标签设置为20的倍数   
    xmajorFormatter = FormatStrFormatter('%d') #设置x轴标签文本的格式   
    #xminorLocator   = MultipleLocator(5) #将x轴次刻度标签设置为5的倍数   

    ymajorLocator   = MultipleLocator(500) #将y轴主刻度标签设置为0.5的倍数   
    ymajorFormatter = FormatStrFormatter('%d') #设置y轴标签文本的格式   
    yminorLocator   = MultipleLocator(50) #将此y轴次刻度标签设置为0.1的倍数 

    print("XS:")
    static_list_XS = statisticSingle("result_XS.txt")
    print("PM:")
    static_list_PM = statisticSingle("result_PM.txt")
    print("MT:")
    static_list_MT = statisticSingle("result_MT.txt")
    print("LCG:")
    static_list_LCG = statisticSingle("result_LCG.txt")

    result_maplist = [{"XS":static_list_XS},{"PM":static_list_PM},{"MT":static_list_MT},{"LCG":static_list_LCG}]
    createAverage(result_maplist)
    
    fig, ax = plt.subplots()
    x_axis=range(1,len(static_list_XS)+1)
    ax.plot(x_axis,static_list_XS, ':s', ms=8, lw=2, alpha=0.8, mfc='blue')
    ax.plot(x_axis,static_list_PM, '-p', ms=8, lw=2, alpha=0.8, mfc='green')
    ax.plot(x_axis,static_list_MT, '-.d', ms=8, lw=2, alpha=0.8, mfc='red')
    ax.plot(x_axis,static_list_LCG, '--o', ms=8, lw=2, alpha=0.8, mfc='cyan')
    ax.set_xlim(0, 11)

    #ax.set_ylim(50, 150)
    ax.legend(("XS","PM","MT","LCG"),loc="upper left")
    #ax.grid()
    
    #设置主刻度标签的位置,标签文本的格式 
    ax.xaxis.set_major_locator(xmajorLocator)  
    ax.xaxis.set_major_formatter(xmajorFormatter)  
  
    ax.yaxis.set_major_locator(ymajorLocator)  
    ax.yaxis.set_major_formatter(ymajorFormatter)
    #显示次刻度标签的位置,没有标签文本   
    #ax.xaxis.set_minor_locator(xminorLocator)  
    ax.yaxis.set_minor_locator(yminorLocator)  
  
    ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度   
    ax.yaxis.grid(True, which='major') #y坐标轴的网格使用次刻度   

    plt.xlabel('Experiment Groups')
    plt.ylabel('Value(lamda*X+(1-lamda)*T)')
    #plt.title('Experiment Results of Different RNGs')
    #plt.axis([0, 4,0,1.0])
    expstring="%f,%f,%f,%f" % (sum(static_list_XS)/len(static_list_XS),sum(static_list_PM)/len(static_list_PM),sum(static_list_MT)/len(static_list_MT),sum(static_list_LCG)/len(static_list_LCG))
    print("expectation:[XS,PM,MT,LCG]=["+expstring+"]")
    plt.savefig(os.getcwd()+"/experiment_results.png")
    plt.show()
    '''
    py_ver = platform.python_version()
    print("press 'Enter' key to exit...")
    if py_ver.startswith("2."):
        raw_input()
    else:
        input()
    '''
